/*
 * @Description: 文件描述
 * @Author: 陈三愿
 * @Date: 2025-08-31 23:09:51
 * @LastEditTime: 2025-10-04 13:22:40
 */
import {
  Controller,
  Get,
  Post,
  Body,
  UnauthorizedException,
  Inject,
  Res,
  Req,
  HttpCode,
} from '@nestjs/common';
import type { Response, Request } from 'express';
import { AuthConfig } from '../auth/auth.config';
import { UserService } from './user.service';
import { AuthService } from '../auth/auth.service';

@Controller('users')
export class UserController {
  constructor(
    private readonly userService: UserService,
    @Inject(AuthService) private readonly authService: AuthService,
  ) {}

  @Get('all')
  getUsers() {
    return [
      { id: 1, name: 'John' },
      { id: 2, name: 'Jane' },
    ];
  }
  @Post('register')
  async register(@Body() body: { username: string; password: string }) {
    return this.userService.createUser(body.username, body.password);
  }

  @Post('login')
  async login(
    @Body() body: { username: string; password: string },
    @Res({ passthrough: true }) response: Response,
  ) {
    console.log('body', body);
    const user = await this.userService.validateUser(
      body.username,
      body.password,
    );
    if (!user) {
      throw new UnauthorizedException('用户名或密码错误');
    }

    // 准备用户载荷
    const payload = {
      userId: user.id,
      username: user.username,
      // 可以添加其他需要的用户信息，但不要包含敏感信息如密码
    };

    // 生成访问令牌
    const accessToken = await this.authService.generateToken(payload);

    // 生成刷新令牌
    const refreshToken = await this.authService.generateRefreshToken(payload);

    // 将刷新令牌设置到 Cookie
    response.cookie(AuthConfig.refreshTokenCookie.name, refreshToken, {
      httpOnly: AuthConfig.refreshTokenCookie.httpOnly,
      secure: AuthConfig.refreshTokenCookie.secure,
      sameSite: AuthConfig.refreshTokenCookie.sameSite,
      maxAge: AuthConfig.refreshTokenCookie.maxAge,
    });

    // 返回访问令牌和用户信息（排除密码）
    const { password, ...userInfo } = user;

    return {
      access_token: accessToken,
      user: userInfo,
    };
  }

  @Post('refresh-token')
  @HttpCode(200)
  async refreshToken(@Req() request: Request) {
    // 从 Cookie 中获取刷新令牌
    const refreshToken = request.cookies?.[AuthConfig.refreshTokenCookie.name];
    console.log('request.cookies', JSON.stringify(request.cookies));
    console.log('refreshToken', refreshToken);

    if (!refreshToken) {
      throw new UnauthorizedException('刷新令牌不存在');
    }

    try {
      // 使用刷新令牌生成新的访问令牌
      const newAccessToken =
        await this.authService.refreshAccessToken(refreshToken);

      // 返回新的访问令牌
      return {
        access_token: newAccessToken,
      };
    } catch (error) {
      throw new UnauthorizedException('刷新令牌已过期或无效');
    }
  }
}
